package com.sinsz.common.wrapper;

import org.springframework.util.StringUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;

/**
 * 重定义流处理
 * @author chenjianbo
 */
public class SinszRequestWrapper extends HttpServletRequestWrapper {

    private final byte[] body;

    public SinszRequestWrapper(HttpServletRequest request) {
        super(request);
        this.body = requestBody(request).getBytes();
    }

    @Override
    public BufferedReader getReader() {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener listener) {

            }

            @Override
            public int read() {
                return bais.read();
            }
        };
    }

    private String requestBody(HttpServletRequest request) {
        try(
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                InputStream is = request.getInputStream()
            ) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            String result = new String(baos.toByteArray(),"UTF-8");
            return StringUtils.isEmpty(result) ? "" : result;
        } catch (IOException ignored) {
        }
        return "";
    }
}
